package com.old.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.old.dto.*;
import com.old.entity.Post;
import com.old.entity.Video;
import com.old.entity.VideoComment;
import com.old.result.PageBean;
import com.old.result.Result;
import com.old.service.HistoryService;
import com.old.service.PostService;
import com.old.service.VideCommentService;
import com.old.service.VideoService;
import com.old.service.impl.Recommendationservice;
import com.old.util.JwtUtil;
import com.old.vo.VideoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;


@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/video")
public class VideoController {
    private final VideoService videoService;

    private final VideCommentService videCommentService;

    private final PostService postService;
    private final HistoryService historyService;
    private final Recommendationservice recommendationservice;

    @RequestMapping("/addVideo")
    public Result addVideo(@RequestBody VideoInsertDTO videoInsertDTO) {
        log.info("add video");
        videoService.addVideo(videoInsertDTO);
        return Result.success();
    }

    //戏曲列表
    @GetMapping("/videoList")
    public Result getVideoList(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String searchTerms,
            @RequestParam (required = false)Integer userId,
            @RequestParam(defaultValue = "0") Integer sortBy
    ) throws JsonProcessingException {
//        PageBean pageList = videoService.pageList(pageNo, pageSize, sortBy, searchTerms, userId);
//        log.info("分页查询: 页码={} 页大小={} 搜索词={} 排序方式={} 总数={}", pageNo, pageSize, searchTerms, sortBy, pageList.getTotal());
//
//        return Result.success(pageList);

        return Result.success(
                recommendationservice.getRecommendedVideos(pageNo,pageSize, sortBy,searchTerms,userId)
        );
    }

    // 戏曲详情
    @GetMapping("/videoInfo")
    public Result getVideoInfo(
            @RequestParam(required = false) Integer commentListId,
            @RequestParam(required = false) Integer videoId,
            @RequestParam(required = false) Integer userId,
            @RequestHeader(value = "Authorization") String token
    ) {

        //TODO 把从token获取改为从线程获取
        if(userId == null){
            userId = JwtUtil.getUserIdFromToken(token);
        }

        if (userId != null) {
            //保存浏览记录
            historyService.saveVideoHistory(userId, videoId);
        }

        VideoVO videoVO = videoService.getVideoDetail(videoId, userId);
        return Result.success(videoVO);
    }


    @GetMapping("/getCommentList")
    public Result<PageBean> getCommentList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam Integer videoId) {

        VideoCommentQueryDTO queryDTO = new VideoCommentQueryDTO();
        queryDTO.setPage(page);
        queryDTO.setPageSize(pageSize);
        queryDTO.setVideoId(videoId);
        return Result.success(videCommentService.commentListPage(queryDTO));
    }
//    // 戏曲评论
//    @GetMapping("/getCommentList")
//    public Result<PageResult> getCommentList(
//            @RequestParam(defaultValue = "1") Integer page,
//            @RequestParam(defaultValue = "10") Integer pageSize,
//            @RequestParam int videoId
//    ) {
//        VideoCommentQueryDTO queryDTO = new VideoCommentQueryDTO();
//        queryDTO.setPage(page);
//        queryDTO.setPageSize(pageSize);
//        queryDTO.setVideoId(videoId);
//        return Result.success(videCommentService.commentListPage(queryDTO));
//    }


     //发表评论
    @PostMapping("/addComment")
    public Result<VideoComment> addComment(@RequestBody VideoAddDTO videoAddDTO) {
        VideoCommentDTO videoCommentDTO = new VideoCommentDTO();
        videoCommentDTO.setComment(videoAddDTO.getComment());
        videoCommentDTO.setCommentAuthorId(Integer.parseInt(videoAddDTO.getCommentAuthorId()));
        videoCommentDTO.setVideoId(Integer.parseInt(videoAddDTO.getVideoId()));
        videoCommentDTO.setCreateTime(LocalDateTime.now());
        videoCommentDTO.setUpdateTime(LocalDateTime.now());
        videCommentService.addComment(videoCommentDTO);
        return Result.success();
    }

    // DTO 转换方法
    private VideoDTO convertToVideoDTO(Video video, Post post) {
        VideoDTO dto = new VideoDTO();
        dto.setId(video.getId());
        dto.setTitle(video.getTitle());
        dto.setVideoUrl(video.getVideoUrl());
        dto.setLike(video.getLikes());
        dto.setLikeMen(video.getLikeMan());
        dto.setImageUrl(video.getImageUrl());
        dto.setContent(video.getContent());
        dto.setAuthorId(video.getAuthorId());
        dto.setGood(video.isGood());

        // 设置作者信息
        if (post != null) {
            dto.setName(post.getName());
            dto.setAvatar(post.getAvatar());
        } else {
            dto.setName("未知用户");
            dto.setAvatar("default-avatar.png");
        }

        // 处理时间格式化
        if (video.getCreateTime() != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            dto.setCreateTime(video.getCreateTime().format(formatter));
        } else {
            dto.setCreateTime("时间未记录");
        }

        return dto;
    }

    // 点赞
    @PutMapping("/like")
    public Result <Map<String, Integer>>likeVideo(@RequestBody VideoLikeDTO likeDTO) {
        Integer likeCount = videoService.likeVideo(likeDTO.getVideoId(), likeDTO.getUserId());
        Map<String, Integer> response = new HashMap<>();
        response.put("like", likeCount);
        return Result.success(response);
    }
    //取消点赞

    @PutMapping("/noLike")
    public Result<Map<String, Integer>> cancelLike(@RequestBody VideoLikeDTO likeDTO) {
        Integer likeCount = videoService.cancelLike(likeDTO.getVideoId(), likeDTO.getUserId());
        Map<String, Integer> response = new HashMap<>();
        response.put("like", likeCount);
        return Result.success(response);
    }

}
